package com.hulk.mybatis.boot.tenant;



import com.hulk.mybatis.boot.tenant.annotation.EnableTenantConfig;


import com.hulk.mybatis.boot.tenant.util.SqlFilterUtil;
import com.hulk.mybatis.boot.tenant.util.TenantContextThreadLocalHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * tenant configuration
 *
 * @author hulk
 */
@Configuration
@ConditionalOnClass(TenantInterceptor.class)
@ConditionalOnBean(annotation = EnableTenantConfig.class)
@EnableConfigurationProperties(TenantProperties.class)
public class TenantAutoConfiguration {


   @Autowired
   private TenantProperties properties;


  @Bean
  //@ConditionalOnMissingBean(value = EnableTenantConfig.class, search = SearchStrategy.CURRENT)
  public TenantInterceptor tenantInterceptor (){

      TenantContextHolder tenantContextHolder = null;
      if(properties.getTenantContextHolder()==null ) {
          tenantContextHolder = new TenantContextThreadLocalHolder();
      }else if (!(TenantContextHolder.class.isInstance(properties.getTenantContextHolder()))){
          tenantContextHolder = new TenantContextThreadLocalHolder();
      }else {
          tenantContextHolder = BeanUtils.instantiateClass(properties.getTenantContextHolder());
      }

    TenantInterceptor  tenantInterceptor =  new TenantInterceptor(properties.getTenantIdColumn(),  tenantContextHolder);
    SqlFilterUtil.addBlackList(properties.getIgnoreTenantTables());
    return  tenantInterceptor;
  }

    public static void main(String[] args) {

    }

}
